<template>
	<view class="m-page">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">隔油池表单</block>
		</cu-custom>
		<view class="margin-top" style="background-color: white; padding-left: 40rpx; padding-right: 40rpx;">
			<u--form
				labelPosition="left"
				labelWidth="80"
				:model="formData"
				:rules="rules"
				ref="uForm"
			>
				<u-form-item
					label="日期选择"
					prop="date"
					borderBottom
					labelWidth="80"
					@click="showDate = true;"
				>
					<u--text :text="formData.createTime"></u--text>
				</u-form-item>
				<u-form-item
					label="规范状态"
					prop="status"
					labelWidth="80"
					borderBottom
				>
					<u-radio-group
					    v-model="formData.status"
					    placement="row"
					    @change="groupChange"
					>
					    <u-radio
					      :customStyle="{marginRight: '20px'}"
					      v-for="(item, index) in radioStatusList"
					      :key="index"
					      :label="item.label"
					      :name="item.name"
					      @change="radioChange"
					    >
					    </u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item
					label="垃圾重量"
					labelWidth="80"
					prop="weight"
					borderBottom
				>
					<u-input
						v-model="formData.weight"
						border="none"
						placeholder="请输入垃圾重量"
					>
						<u--text
						    @click="showWeight=true;"
							:text="merchant.orgCode == 'A05' ? 'KG（快速选择）' : '桶'"
							slot="suffix"
							margin="0 3px 0 0"
							type="tips"
						></u--text>
					</u-input>
				</u-form-item>
				<u-form-item
					label="清理前"
					prop="beforeUpload"
					labelWidth="80"
					borderBottom
					labelPosition="left"
				>
					<u-upload
						:fileList="formData.beforeUpload"
						@afterRead="afterRead1"
						@delete="deletePic1"
						name="before"
						multiple
						:maxCount="1"
						width="250"
						height="190"
					>
						<image :src="beforeUploadPreview" 
													mode="widthFix" style="width: 250px;height: 190px;"></image>
					</u-upload>
				</u-form-item>
				<u-form-item
					label="清理后"
					prop="afterUpload"
					labelWidth="80"
					borderBottom
					labelPosition="left"
				>
					<u-upload
						:fileList="formData.afterUpload"
						@afterRead="afterRead2"
						@delete="deletePic2"
						name="after"
						multiple
						:maxCount="1"
						width="250"
						height="190"
					>
						<image :src="afterUploadPreview" 
													mode="widthFix" style="width: 250px;height: 190px;"></image>
					</u-upload>
				</u-form-item>
			</u--form>
			<u-gap height="15" bgColor="#fff"></u-gap>
			<u--text v-if="token" iconStyle="color: #f1a532" :text="'当前商户为' + merchant.name + ',请确认!'" prefixIcon="error" align="center" type="warning"></u--text>
			<u-gap height="15" bgColor="#fff"></u-gap>
			<u-button v-if="token" text="提交" type="primary" @click="submitForm"></u-button>
			<u-gap height="20" bgColor="#fff" v-if="id && token"></u-gap>
			<u-button text="删除" type="error" @click="deleteForm" v-if="id && token"></u-button>
			<u-gap height="30" bgColor="#fff"></u-gap>
		</view>
		<u-datetime-picker
			style="position: absolute;"
			:show="showDate"
			v-model="showTimestamp"
			mode="datetime"
			:closeOnClickOverlay="true"
			@confirm="changeDate" @close="cancelDate" @cancel="cancelDate"
		>
		</u-datetime-picker>
		<u-picker :show="showWeight" title="选择垃圾重量" :columns="weightColumn" :defaultIndex="selectedWeightIndex" keyName="name" :closeOnClickOverlay="true" @change="changeWeight" @confirm="showWeight=false;" @close="showWeight=false;" @cancel="showWeight=false;"></u-picker>
		<u-modal :show="showDelete" title="警告" content="删除后不可恢复,确定要删除吗？" :showCancelButton="true" @confirm="confirmDelete" :closeOnClickOverlay="true" @close="showDelete = false;" @cancel="showDelete = false;"></u-modal>
		<!-- 加载弹窗 -->
		<view class="cu-load load-modal" v-if="loading">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<image src="https://mini.wm-mis.com/img/static/car.png" mode="aspectFit" class="round"></image>
			<view class="gray-text">加载中...</view>
		</view>
	</view>
</template>

<script>
	import moment from 'moment';
	import {
		mapState
	} from 'vuex';
	import api from '@/api/api'
	import configService from '@/common/service/config.service.js';
	import {ACCESS_TOKEN} from '@/common/util/constants.js'
	
	export default {
		computed: {
			...mapState([
				'merchant',
				'token'
			])
		},
		data() {
			return {
				id: '',
				detail: null,
				radioStatusList: [
					{
						label: '规范',
						name: 'STANDARD', //v-model绑定的值
						disabled: false
					},
					{
						label: '不规范',  
						name: 'NONSTANDARD',
						disabled: false
					}
				],
				loading: false,
				showDate: false,
				showTimestamp: (new Date()).getTime(),
				showDelete: false,
				formData: {
					weight: '',
					beforeUpload: [],
					afterUpload: [],
					status: 'NONSTANDARD',
					createTime: moment((new Date()).getTime()).format('YYYY-MM-DD HH:MM:SS'),
					fkShopId: ''
				},
				rules: {
					'weight': {
						type: 'string',
						required: true,
						transform(value) {
							return String(value);
						},
						message: '请输入垃圾重量',
						trigger: ['blur', 'change']
					},
					'status': {
						type: 'string',
						required: true,
						message: '请输入规范状态',
						trigger: ['blur', 'change']
					},
					'createTime': {
						type: 'string',
						required: true,
						message: '请选择日期',
						trigger: ['blur', 'change']
					}
				},
				beforeUploadPreview: 'https://mini.wm-mis.com/img/static/pic_placeholder.png',
				afterUploadPreview: 'https://mini.wm-mis.com/img/static/pic_placeholder.png',
				showWeight: false,
				selectedWeightIndex: [0],
				weightColumn: [
					[
						{
							name: '10',
							label: '10'
						},
						{
							name: '20',
							label: '20'
						},
						{
							name: '30',
							label: '30'
						},
						{
							name: '40',
							label: '40'
						},
						{
							name: '50',
							label: '50'
						}
					]
				]
			};
		},
		async onLoad(options){
			this.id = options.id
			if(this.id){
				await this.getDetail();
			}
		},
		mounted(){
			this.formData.fkShopId = this.merchant ? this.merchant.id : ''
			if(this.merchant.orgCode == 'A05' && !this.id){
				this.formData.weight = 10
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			async getDetail(){
				let that = this
				that.loading = true
				let res = await api.oilDetail({
					id: that.id
				})
				if(res.data.code == 200 && res.data.success){
					that.detail = res.data.result
					that.formData.weight = that.detail.weight
					that.formData.createTime = that.detail.createTime
					that.formData.remark = that.detail.remark
					that.formData.status = that.detail.status
					if(that.detail.afterUpload){
						that.afterUploadPreview = configService.apiUrl + '/sys/common/static/' + that.detail.afterUpload
					}
					else{
						that.afterUploadPreview = 'https://mini.wm-mis.com/img/static/pic_placeholder.png';
					}
					
					if(that.detail.beforeUpload){
						that.beforeUploadPreview = configService.apiUrl + '/sys/common/static/' + that.detail.beforeUpload
					}
					else{
						that.beforeUploadPreview = 'https://mini.wm-mis.com/img/static/pic_placeholder.png';
					}
					
					that.showTimestamp = new Date(that.detail.createTime).getTime()
				}
				that.loading = false
			},
			groupChange(n) {
				//console.log('groupChange', n);
			},
			radioChange(n) {
				//console.log('radioChange', n);
			},
			//确认日期
			changeDate(value){
				this.showDate = false;
				let date = moment(Number(value.value)).format('YYYY-MM-DD HH:MM:SS');
				this.formData.createTime = date;
			},
			cancelDate() {
				this.showDate = false;
			},
			changeWeight(e){
				const {
					indexs,
					value
				} = e
							
				let that = this;
				
				//选中的设备
				let selectIndex = indexs[0];
				let weight = that.weightColumn[0][selectIndex].name;
				that.selectedWeightIndex = [selectIndex];
				that.formData.weight = weight
			},
			// 删除图片
			deletePic1(event) {
				this.formData['beforeUpload'].splice(event.index, 1)
			},
			// 新增图片
			async afterRead1(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData['beforeUpload'].length
				lists.map((item) => {
					this.formData['beforeUpload'].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.formData['beforeUpload'][fileListLen]
					this.formData['beforeUpload'].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))

					fileListLen++
				}
			},
			// 删除图片 
			deletePic2(event) {
				this.formData['afterUpload'].splice(event.index, 1)
			},
			// 新增图片
			async afterRead2(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData['afterUpload'].length
				lists.map((item) => {
					this.formData['afterUpload'].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.formData['afterUpload'][fileListLen]
					this.formData['afterUpload'].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			async uploadFilePromise(url) {
				let header = {
					'X-Access-Token': uni.getStorageSync(ACCESS_TOKEN)
				};

				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						header: header,
						url: configService.apiUrl + '/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let response = JSON.parse(res.data)
							resolve(response.message)
						}
					});
				})
			},
			async submitForm(){
				let that = this
				let res = null;
				if(!that.id){
					// if(that.formData['beforeUpload'].length == 0){
					// 	uni.showToast({
					// 		icon: 'error',
					// 		title: '上传清理前图片',
					// 		duration: 2000
					// 	})
					// 	return;
					// }
					// if(that.formData['afterUpload'].length == 0){
					// 	uni.showToast({
					// 		icon: 'error',
					// 		title: '上传清理后图片',
					// 		duration: 2000
					// 	})
					// 	return;
					// }
					
					that.loading = true
					res = await api.oilAdd({
						weight: that.formData.weight,
						createTime: that.formData.createTime,
						status: that.formData.status,
						afterUpload: that.formData['afterUpload'][0] ? that.formData['afterUpload'][0].url : '',
						beforeUpload: that.formData['beforeUpload'][0] ? that.formData['beforeUpload'][0].url : '',
						fkShopId: that.formData.fkShopId
					})
				}
				else{
					let beforeUpload = that.formData['beforeUpload'].length != 0 ? that.formData['beforeUpload'][0].url : that.detail.beforeUpload
					let afterUpload = that.formData['afterUpload'].length != 0 ? that.formData['afterUpload'][0].url : that.detail.afterUpload
					
					that.loading = true
					res = await api.oilUpdate({
						id: that.id,
						weight: that.formData.weight,
						createTime: that.formData.createTime,
						status: that.formData.status,
						afterUpload: afterUpload,
						beforeUpload: beforeUpload,
						fkShopId: that.formData.fkShopId
					})
				}
				that.loading = false
				if(res.data.code == 200 && res.data.success){
					uni.setStorageSync('entryDetail', 'oilDetail')//添加操作标记，返回时需要刷新
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
					
					setTimeout(()=>{
						uni.navigateBack();
					}, 2000)
				}
			},
			async deleteForm(){
				this.showDelete = true
			},
			async confirmDelete(){
				let that = this
				that.showDelete = false
				that.loading = true
				let res = await api.oilDelete({
					id: that.id
				})
				if(res.data.code == 200 && res.data.success){
					uni.setStorageSync('entryDetail', 'oilDetail')//添加操作标记，返回时需要刷新
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
					
					that.loading = false
					setTimeout(()=>{
						uni.navigateBack();
					}, 2000)
				}
				that.loading = false
			},
		}
	}
</script>

<style scoped>
	.m-page{
		height: 100%;
		background-color: #f4f4f4;
	}
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>
